/**
# Run

xmake run -- two-vector-add_bench --benchmark_counters_tabular=true
*/

#include <benchmark/benchmark.h>

#include <random>
#include <sstream>
#include <two-vector-add.hpp>

#include "malloc_hook.hpp"

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> uid(0, 9);

// 清理链表内存
void cleanup_list(ListNode* head) {
    while (head) {
        ListNode* temp = head;
        head = head->next;
        delete temp;
    }
}

// 创建大规模测试用例
std::pair<ListNode*, ListNode*> create_large_test_case() {
    ListNode* l1 = new ListNode(uid(gen));
    ListNode* l2 = new ListNode(uid(gen));
    ListNode* curr1 = l1;
    ListNode* curr2 = l2;

    // 创建长度为1000的链表
    for (int i = 0; i < 999; ++i) {
        curr1->next = new ListNode(uid(gen));
        curr2->next = new ListNode(uid(gen));
        curr1 = curr1->next;
        curr2 = curr2->next;
    }

    return {l1, l2};
}

// 基准测试：answer 函数 - 大规模
static void BM_Answer_Large(benchmark::State& state) {
    BEFORE_TEST
    for (auto _ : state) {
        auto [l1, l2] = create_large_test_case();

        std::ostringstream output;
        std::streambuf* origCout = std::cout.rdbuf(output.rdbuf());

        answer(l1, l2);

        std::cout.rdbuf(origCout);

        cleanup_list(l1);
        cleanup_list(l2);
    }
    AFTER_TEST
}

// 基准测试：ai_answer 函数 - 大规模
static void BM_AIAnswer_Large(benchmark::State& state) {
    BEFORE_TEST
    for (auto _ : state) {
        auto [l1, l2] = create_large_test_case();

        std::ostringstream output;
        std::streambuf* origCout = std::cout.rdbuf(output.rdbuf());

        ai_answer(l1, l2);

        std::cout.rdbuf(origCout);

        cleanup_list(l1);
        cleanup_list(l2);
    }
    AFTER_TEST
}

// 基准测试：ai_answer 函数 - 大规模
static void BM_OfficialAnswer_Large(benchmark::State& state) {
    BEFORE_TEST
    for (auto _ : state) {
        auto [l1, l2] = create_large_test_case();

        std::ostringstream output;
        std::streambuf* origCout = std::cout.rdbuf(output.rdbuf());

        official_answer(l1, l2);

        std::cout.rdbuf(origCout);

        cleanup_list(l1);
        cleanup_list(l2);
    }
    AFTER_TEST
}

// 注册基准测试
// 设置最小运行时间10秒，提高统计意义
BENCHMARK(BM_Answer_Large)->MinTime(10)->Unit(benchmark::kMillisecond);
BENCHMARK(BM_AIAnswer_Large)->MinTime(10)->Unit(benchmark::kMillisecond);
BENCHMARK(BM_OfficialAnswer_Large)->MinTime(10)->Unit(benchmark::kMillisecond);

BENCHMARK_MAIN();